package com.wzb.mybatisplus.bitaction.electrumaction.one;

import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class BitcoinService {

    public static double maney = 0;

    public static int size = 0;


    public static JSONObject getBalanceJson(String bitcoinAddress) {
        try {
            String url = "https://blockchain.info/balance?active=" + bitcoinAddress;
            String response = sendGetRequest(url);
            for(;response==null;){
                Thread.sleep(1000);
                response = sendGetRequest(url);
            }


            JSONObject jsonResponse = new JSONObject(response);
            JSONObject addressInfo = jsonResponse.getJSONObject(bitcoinAddress);
//            long satoshis = addressInfo.getLong("final_balance");
//            int jiaoyiliang = addressInfo.getInt("n_tx");
//            long total_received = addressInfo.getLong("total_received");
//            System.out.println("金额："+satoshis);
//            if(jiaoyiliang>0){
//                return jiaoyiliang;
//            }


//            int s = 5/0;
            return addressInfo ;

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
            return null;
        }
    }

    // 使用Blockchain.info API查询余额
    public static double getBalance(String bitcoinAddress) {
        try {
            String url = "https://blockchain.info/balance?active=" + bitcoinAddress;
            String response = sendGetRequest(url);
            JSONObject jsonResponse = new JSONObject(response);
            JSONObject addressInfo = jsonResponse.getJSONObject(bitcoinAddress);
            long satoshis = addressInfo.getLong("final_balance");
//            int jiaoyiliang = addressInfo.getInt("n_tx");
//            long total_received = addressInfo.getLong("total_received");
            System.out.println("金额："+satoshis);


//            int s = 5/0;
            return satoshis ;

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
            return 0.0;
        }
    }

    // 获取交易记录
    public static List<BitcoinTransaction> getTransactions(String bitcoinAddress, int limit) {
        List<BitcoinTransaction> transactions = new ArrayList<>();
        try {
            String url = "https://blockchain.info/rawaddr/" + bitcoinAddress + "?limit=" + limit;
            String response = sendGetRequest(url);
            JSONObject jsonResponse = new JSONObject(response);

            JSONArray txs = jsonResponse.getJSONArray("n_tx");
            for (int i = 0; i < txs.length(); i++) {
                JSONObject tx = txs.getJSONObject(i);
                BitcoinTransaction transaction = parseTransaction(tx, bitcoinAddress);
                transactions.add(transaction);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return transactions;
    }

    // 解析交易数据
    private static BitcoinTransaction parseTransaction(JSONObject tx, String address) {
        BitcoinTransaction transaction = new BitcoinTransaction();
        transaction.setTxHash(tx.getString("hash"));
        transaction.setBlockHeight(tx.optLong("block_height", 0));
        transaction.setTimestamp(tx.getLong("time"));
//        transaction.setConfirmations(tx.getInt("confirmations"));

        // 计算交易金额
        long inputValue = 0;
        long outputValue = 0;

        // 分析输入
        JSONArray inputs = tx.getJSONArray("inputs");
        for (int j = 0; j < inputs.length(); j++) {
            JSONObject input = inputs.getJSONObject(j);
            JSONObject prevOut = input.getJSONObject("prev_out");
            if (prevOut.has("addr") && address.equals(prevOut.getString("addr"))) {
                inputValue += prevOut.getLong("value");
            }
        }

        // 分析输出
        JSONArray outputs = tx.getJSONArray("out");
        for (int k = 0; k < outputs.length(); k++) {
            JSONObject output = outputs.getJSONObject(k);
            if (output.has("addr") && address.equals(output.getString("addr"))) {
                outputValue += output.getLong("value");
            }
        }

        // 计算净额（正数为收入，负数为支出）
        long netAmount = outputValue - inputValue;
        transaction.setAmount(netAmount / 100000000.0);
        transaction.setDirection(netAmount >= 0 ? "IN" : "OUT");

        return transaction;
    }

    // 发送HTTP GET请求
    private static String sendGetRequest(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();

        } catch (Exception e) {
//            throw new RuntimeException("API请求失败: " + e.getMessage());
            return null;
        }
    }
}